// packageA/pages/attendanceGroupAdd/attendanceGroupAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //是否是修改
    isEdit:false,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //避免表单重复提交
    code:null,
    //考勤规则
    showRule: false,
    //考勤规则列表
    ruleList: [],
    //考勤规则全选/反选
    checkedAll: false,
    //考勤规则选项
    checkDetail: [],
    //考勤规则选项数量
    checkLen: 0,
    //围栏选择框
    showFence: false,
    //围栏列表
    fenceList: [],
    //围栏全选/反选
    checkedAllFence: false,
    //围栏选项
    checkDetailFence: [],
    //围栏选项数量
    checkLenFence: 0,
    //区域选择框
    showArea: false,
    //区域列表
    areaList: [],
    //区域全选/反选
    checkedAllArea: false,
    //区域选项
    checkDetailArea: [],
    //区域选项数量
    checkLenArea: 0,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //是否有排班
    isHavePlan: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      code:Base64.encode(new Date() + app.globalData.userInfo.userName)
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('考勤传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id,
          isEdit: true
        })

        //查询考勤组是否已排班
        this.isExistPlan();

        //获取修改数据
        this.getInfo();
      }
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let user=app.globalData.userInfo;

    //非空验证
    let name=obj.name.trim();
    if(!this.formNotEmpty(name,'nameMessage','请输入考勤组名称')){
      return;
    }

    if(!editInfo.workArea){
      Toast.fail('请选择清洁区域');
      return;
    }

    if(!editInfo.fences){
      Toast.fail('请选择考勤地点');
      return;
    }

    if(!editInfo.attendanceShifts){
      Toast.fail('请选择考勤班次');
      return;
    }

    //权限
    let authArr=[user.depart, user.departObj[0].companyId, editInfo.depart.id];
    authArr=util.arrayRepeatEmpty(authArr);

    let param={
      className:'attendanceGroup',
      data:{
        requestToken: td.code,
        id: td.id,
        //名称
        name: name,
        //规则/班次
        attendanceShifts: editInfo.attendanceShifts,
        //围栏/地点
        fences: editInfo.fences,
        //清洁区域
        workArea: editInfo.workArea,
        //项目
        depart: editInfo.depart,
        departId: editInfo.depart.id,
        dataAuthority: {
          depart: authArr
        },
        appId: [app.globalData.myAppId]
      }
    }

    console.log(param)
    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });
    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        if (param.data.id!=null && param.data.id !=""){
          CommonService.syncEmployeeSchedulingArea({id:param.data.id,
            name:param.data.name,attendanceShifts:param.data.attendanceShifts}).then(res=>{

          })
        }
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'attendanceGroup',
      data: {
        id:this.data.id,
        selectFields: ['id','name','attendanceShifts','fences','workArea','depart']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //清洁区域显示和初始化选中状态
        if(result.workArea && result.workArea.length){
          let self_area=[];
          let checkDetailArea=[];

          result.workArea.forEach(item => {
            self_area.push(item.name);
            checkDetailArea.push(item.id+'');
          });

          result.self_area=self_area;
          this.setData({
            checkDetailArea: checkDetailArea
          })
        }

        //地点显示和初始化选中状态
        if(result.fences && result.fences.length){
          let self_fence=[];
          let checkDetailFence=[];

          result.fences.forEach(item => {
            self_fence.push(item.name);
            checkDetailFence.push(item.id+'');
          });

          result.self_fence=self_fence;
          this.setData({
            checkDetailFence: checkDetailFence
          })
        }

        //班次显示和初始化选中状态
        if(result.attendanceShifts && result.attendanceShifts.length){
          let self_ruleName=[];
          let checkDetail=[];

          result.attendanceShifts.forEach(item => {
            self_ruleName.push(item.ruleName);
            checkDetail.push(item.id+'');
          });

          result.self_ruleName=self_ruleName;
          this.setData({
            checkDetail: checkDetail
          })
        }

        console.log('考勤组信息回显');
        console.log(result);

        this.setData({
          editInfo: result
        })

        //查询区域
        this.getAreaList();

        //查询围栏
        this.getFenceList();

        //查询考勤规则
        this.getRuleList();
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示考勤规则
  onShowRule(){
    if(this.data.editInfo.depart){
      this.setData({
        showRule: true
      })
    }else{
      Toast.fail('请先选择项目');
    }
  },

  //隐藏考勤规则
  onCloseRule(){
    this.setData({
      showRule: false
    })
  },

  //添加考勤规则
  goToAdd(){
    wx.navigateTo({
      url: "/packageA/pages/attendanceRuleAdd/attendanceRuleAdd"
    })
  },

  //查询考勤规则
  getRuleList(){
    this.setData({
      ruleList: [],
      checkLen: 0
    })

    let param = {
      isAuth: true,
      className: 'clockRule',
      data: {
        searchAll: true,
        departId: this.data.editInfo.depart.id,
        selectFields: ['id','ruleName','ruleTime'],
        sort: {id: -1}
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        console.log('考勤规则列表');
        console.log(result);

        this.setData({
          ruleList: result,
          checkLen: result.length
        })
      }
    }).catch((error) => {
    })
  },

  //点击全选
  onChangeAll(event) {
    this.setData({
      checkedAll: event.detail,
    })

    if(event.detail){
      let list=this.data.ruleList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+'');
      })
      this.setData({
        checkDetail: arr,
      })
    }else{
      this.setData({
        checkDetail: [],
      })
    }
  },

  //点击明细选项
  onChangeDetail(event) {
    this.setData({
      checkDetail: event.detail
    })

    if(event.detail.length==this.data.checkLen){
      this.setData({
        checkedAll: true
      })
    }else{
      this.setData({
        checkedAll: false
      })
    }
  },

  //确定考勤规则
  onConfirmRule(){
    let checkDetail=this.data.checkDetail;
    console.log("checkDetail");
    console.log(checkDetail);
    if(checkDetail.length){
      let ruleList=this.data.ruleList;
      console.log("ruleList");
      console.log(ruleList);
      let arr=[];
      ruleList.forEach(item => {
        for(let i=0;i<checkDetail.length;i++){
          if(checkDetail[i]==item.id){
            arr.push(item);
          }
        }
      });

      //显示名称
      let name='editInfo.self_ruleName';
      //接口保存数据
      let attendanceShifts='editInfo.attendanceShifts';

      if(arr.length>1){
        //将排序的字段clockInTime拿出来，去掉冒号后比较数字大小
        arr.forEach(item => {
          item.self_sortTime=(item.ruleTime[0].clockInTime).replace(':','');
        });

        //考勤规则数组按时间先后排序
        arr.sort(util.compareobjectArray('self_sortTime',1));
      }
      console.log("arr");
      console.log(arr);

      //显示的名称
      let names=[];
      arr.forEach(item => {
        names.push(item.ruleName);
      });

      this.setData({
        [name]: names,
        [attendanceShifts]: arr,
        showRule: false,
        disabled: false
      })

      console.log(arr);

    }else{
      Toast.fail('请选择考勤规则');
    }
  },

  //显示围栏
  onShowFence(){
    if(this.data.editInfo.depart){
      this.setData({
        showFence: true
      })
    }else{
      Toast.fail('请先选择项目');
    }
  },

  //隐藏围栏
  onCloseFence(){
    this.setData({
      showFence: false
    })
  },

  //查询围栏
  getFenceList(){
    this.setData({
      fenceList: [],
      checkLenFence: 0
    })

    let param = {
      isAuth: true,
      className: 'personnelFence',
      data: {
        searchAll: true,
        departId: this.data.editInfo.depart.id,
        selectFields: ['id','name','lat','lng','points','radius','type'],
        sort: {id: -1}
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('围栏列表');
        console.log(result);

        this.setData({
          fenceList: result,
          checkLenFence: result.length
        })
      }
    }).catch((error) => {
    })
  },

  //点击全选围栏
  onChangeAllFence(event) {
    this.setData({
      checkedAllFence: event.detail,
    })

    if(event.detail){
      let list=this.data.fenceList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+'');
      })
      this.setData({
        checkDetailFence: arr,
      })
    }else{
      this.setData({
        checkDetailFence: [],
      })
    }
  },

  //点击围栏明细选项
  onChangeDetailFence(event) {
    this.setData({
      checkDetailFence: event.detail,
    })

    if(event.detail.length==this.data.checkLenFence){
      this.setData({
        checkedAllFence: true,
      })
    }else{
      this.setData({
        checkedAllFence: false,
      })
    }
  },

  //确定围栏
  onConfirmFence(){
    let checkDetail=this.data.checkDetailFence;
    if(checkDetail.length){
      let list=this.data.fenceList;
      let arr=[];
      let names=[];

      list.forEach(item => {
        for(let i=0;i<checkDetail.length;i++){
          if(checkDetail[i]==item.id){
            arr.push(item);
            names.push(item.name);
          }
        }
      });

      //显示名称
      let self_name='editInfo.self_fence';
      //接口保存数据
      let fences='editInfo.fences';

      this.setData({
        [self_name]: names,
        [fences]: arr,
        showFence: false,
        disabled: false
      })
    }else{
      Toast.fail('请选择围栏');
    }
  },

  //显示区域
  onShowArea(){
    if(this.data.editInfo.depart){
      this.setData({
        showArea: true
      })
    }else{
      Toast.fail('请先选择项目');
    }
  },

  //隐藏区域
  onCloseArea(){
    this.setData({
      showArea: false
    })
  },

  //查询区域
  getAreaList(){
    this.setData({
      areaList: [],
      checkLenArea: 0
    })

    let param = {
      isAuth: true,
      className: 'workArea',
      data: {
        searchAll: true,
        projectId: this.data.editInfo.depart.id,
        selectFields: ['id','name','project'],
        sort: {id: -1}
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        console.log('区域列表');
        console.log(result);

        this.setData({
          areaList: result,
          checkLenArea: result.length
        })
      }
    }).catch((error) => {
    })
  },

  //点击全选区域
  onChangeAllArea(event) {
    this.setData({
      checkedAllArea: event.detail,
    })

    if(event.detail){
      let list=this.data.areaList;
      let arr=[];
      list.forEach(item => {
        arr.push(item.id+'');
      })
      this.setData({
        checkDetailArea: arr,
      })
    }else{
      this.setData({
        checkDetailArea: [],
      })
    }
  },

  //点击区域明细选项
  onChangeDetailArea(event) {
    console.log("event");
    console.log(event);
    this.setData({
      checkDetailArea: event.detail
    })

    if(event.detail.length==this.data.checkLenArea){
      this.setData({
        checkedAllArea: true
      })
    }else{
      this.setData({
        checkedAllArea: false
      })
    }
  },

  //确定区域
  onConfirmArea(){
    let checkDetail=this.data.checkDetailArea;
    console.log(checkDetail);
    console.log(this.data.areaList);
    if(checkDetail.length){
      let list=this.data.areaList;
      let arr=[];
      let names=[];

      list.forEach(item => {
        for(let i=0;i<checkDetail.length;i++){
          if(checkDetail[i]==item.id){
            arr.push(item);
            names.push(item.name);
          }
        }
      });

      //显示名称
      let self_name='editInfo.self_area';
      //接口保存数据
      let items='editInfo.workArea';

      this.setData({
        [self_name]: names,
        [items]: arr,
        showArea: false,
        disabled: false
      })
    }else{
      Toast.fail('请选择清洁区域');
    }
  },

  //显示选择框
  onShowSelect(e){
    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    if (this.data.isEdit && this.data.isHavePlan && field=='depart'){
      return;
    }

    this.setData({
      selectList: []
    })

    this.setData({
      showSelect: true,
      selectField: field
    })

    //项目
    if(field=='depart'){
      this.setData({
        selectTitle: '项目',
        showSelectSearch: true
      })
      this.getDepartList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;
    let detail=e.detail.value;

    //项目
    if(selectField=='depart'){
      //查询此项目是否已设置了考勤组
      let flag=this.isExist(detail.id).then(value => {
        if (value){
          Toast.fail('此项目已设置过考勤组了，请选择其他项目');
          return;
        }
        return !value;
      });

      //有Promise时
      Promise.all([flag]).then(value => {
        let passed=value.every(val=>{
          return val;
        });
        if(passed){
          //更改了项目后，区域、地点、班次都要重新选择
          let departOld=this.data.editInfo.depart;

          if(departOld && departOld.id!=detail.id){
            let self_area='editInfo.self_area';
            let workArea='editInfo.workArea';
            let self_fence='editInfo.self_fence';
            let fences='editInfo.fences';
            let self_ruleName='editInfo.self_ruleName';
            let attendanceShifts='editInfo.attendanceShifts';

            this.setData({
              [self_area]: null,
              [workArea]: null,
              [self_fence]: null,
              [fences]: null,
              [self_ruleName]: null,
              [attendanceShifts]: null
            })
          }
          obj='editInfo.depart';

          if(id && name){
            this.setData({
              [id]: detail.id,
              [name]: detail.text
            })
          }

          if(obj){
            this.setData({
              [obj]: detail.obj
            })
          }

          this.onCloseSelect();

          //先查出选项数据，而不是点击时再查，这样只请求一次，且二次选择时数据还在
          //查询区域
          this.getAreaList();
          //查询围栏
          this.getFenceList();
          //查询考勤规则
          this.getRuleList();
        }
      });
    }
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //项目
    if(selectField=='depart'){
      this.getDepartList();
    }
  },

  //查询项目
  getDepartList(){
    let param = {
      isAuth: true,
      className: 'depart',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询此项目是否已设置了考勤组
  isExist(depart){
    let param={
      isAuth:true,
      className:'attendanceGroup',
      data:{
        departId: depart,
        selectFields:["id"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.result.length) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //查询考勤组是否已排班
  isExistPlan(){
    let param = {
      isAuth: true,
      className: 'employeeSchedulingArea',
      data: {
        attendanceGroupId: this.data.id,
        selectFields: ['id']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        //是否有排班
        this.setData({
          isHavePlan: true
        })
      }
    }).catch((error) => {
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})
